﻿using RockBus.Logging.Interfaces;
using System;
using System.Reflection;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;

namespace RockBus.Hosting
{
    public abstract class RockBusWebServiceHost : WebServiceHost
    {
        protected RockBusWebServiceHost(ILogger logger, Type serviceType, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        {
            this.Logger = logger;
        }

        protected ILogger Logger { get; private set; }

        private bool _wasOpened;

        protected override void OnOpening()
        {
            this._wasOpened = true;
            base.OnOpening();
        }

        protected override void OnOpened()
        {
            base.OnOpened();
            this.LogHostDetails("Opened ServiceHost on the following endpoints:");
        }

        protected override void OnClosing()
        {
            // Prevent logging if we are creating the ServiceHost only to determine the address
            if (this._wasOpened)
            {
                this.LogHostDetails("Closing ServiceHost on the following endpoints:");
            }

            base.OnClosing();
        }

        protected virtual void LogHostDetails(string description)
        {
            var sb = new StringBuilder(string.Format("Service: {0}. ", this.Description.Name));
            sb.AppendLine(description);

            foreach (ServiceEndpoint se in this.Description.Endpoints)
            {
                sb.AppendFormat("{0}, {1}, {2}",
                    se.Contract.ContractType.Name,
                    se.Binding.Name,
                    se.Address.Uri.ToString());
                sb.AppendLine();
            }

            this.Logger.LogInfo(MethodBase.GetCurrentMethod(), sb.ToString());
        }
    }
}